package com.m4f.city.web.controller;


import java.security.Principal;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import com.m4f.city.business.domain.InternalUser;
import com.m4f.city.business.service.ifc.IServiceLocator;
import com.m4f.gaeweb.exception.M4FException;
import com.m4f.gaeweb.web.base.controller.GaeBaseController;


public abstract class BaseController extends GaeBaseController {	
	private static final Logger LOGGER = Logger.getLogger(BaseController.class.getName());
	
	@Autowired
	protected IServiceLocator serviceLocator;
	
	protected InternalUser getInternalUser(Principal principal) throws M4FException {
		InternalUser user = null;
		if(principal instanceof UsernamePasswordAuthenticationToken) {
			user = (InternalUser) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
		} else if(principal instanceof OAuth2Authentication) {
			user = (InternalUser) ((OAuth2Authentication) principal).getPrincipal();
		}
		
		if(user != null) {
			try {
				InternalUser reloadedUser = this.serviceLocator.getUserService().getUser(user.getId());
				reloadedUser.setAuthorities(user.getAuthorities()); // Setting the authorities from the user of the Securitycontext.
				return reloadedUser;
			} catch(Exception e) {
				LOGGER.warning("Reloading the user data it has not been founded. Returning the user from the security context!");
				return user;
			}
		} else {
			throw new M4FException("Imposible to recognize the authentication token"); // TODO create an exception about user or oauth problems
		}
	}
}